const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json())

const fs = require('fs');

//获取客户端 ip 地址
app.use(function (request, response, next) {
    response.setHeader('Access-Control-Allow-Origin', "*");
    response.setHeader('Access-Control-Allow-Headers', "*");
    response.setHeader('Access-Control-Allow-Methods', "*");
    next();
});
/**
 * 请求类型:   POST
 * 请求URL:   http://192.168.36.25/login
 * 响应结果:  json
 * 参数:      
 *          username   必填 
 *          password   必填
 * 响应示例:
 *  {
 *     "code": "000",
 *     "msg" : "登录成功"
 *  }
 */
app.all('/login', (req, res) => {
    if (req.method.toUpperCase() !== 'POST') {
        return res.json({
            msg: '请求类型错误',
            code: '001'
        })
    }

    //判断
    if (!req.body.username || !req.body.password) {
        return res.json({
            msg: '用户名或密码不能为空',
            code: '002'
        })
        
    }
    if(req.body.username !=='admin' || req.body.password!=='admin'){
        return res.json({
            msg: '登录失败!! 用户名或密码错误',
            code: '003'
        })
    }

    res.json({
        code: '000',
        msg: '登录成功'
    });
});
//目标资源
app.all('/server', (req, res) => {
    res.send('这里是服务器');
});

app.all('/delay-server', (req, res) => {
    setTimeout(() => {
        res.send('这里是服务器');
    }, 3000);
});


app.all('/test', (req, res) => {
    res.send('测试服务');
})

app.all('*', (req, res) => {
    if(req.method.toUpperCase() === 'OPTIONS'){
        res.status(200).end('ok');
        return;
    }
    res.status(404);
    res.end('not found');
})

app.listen(8090, () => {
    console.log('服务已经启动....8090');
});
